package com.tristia.service.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tristia.entity.Good;
import com.tristia.service.GoodService;

@Service("goodService")
public class GoodServiceJpa implements GoodService {

	private EntityManager entityManager;

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}
	
	@Transactional(readOnly = true)
	public Good getById(long id) {
		// TODO Auto-generated method stub
		return entityManager.find(Good.class, id);
	}
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Good> getAll() {
		Query query = entityManager.createNamedQuery("Good.findAll");
		List<Good> goods = null;
		goods = query.getResultList();
		return goods;
	}

	@Transactional(readOnly=false, propagation=Propagation.REQUIRED)
	public boolean save(Good good) {
		
		entityManager.persist(good);
		entityManager.flush();
		
		return true;
	}
	@Transactional(readOnly=false, propagation=Propagation.REQUIRED)
	public boolean update(Good good) {
		entityManager.merge(good);
		entityManager.flush();
		return true;
	}
	@Transactional(readOnly=false, propagation=Propagation.REQUIRED)
	public boolean delete(Good good) {
		good = entityManager.getReference(Good.class, good.getId());
		if (good == null)
			return false;
		entityManager.remove(good);
		entityManager.flush();
		return true;
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public Good findGood(Good good) {
		Good result = null;
		Query queryFindGood = entityManager.createNamedQuery("Good.findGood");
		queryFindGood.setParameter("title", good.getTitle());
		queryFindGood.setParameter("author", good.getAuthor());
		List<Good> goods = queryFindGood.getResultList();
		if(goods.size() > 0) {
			result = goods.get(0);
		}
		return result;
	}
}
